let express = require('express');
let app = new express();
let server = require('http').createServer(app);
let io = require('socket.io').listen(server);

server.listen(8000);



app.use(express.static(__dirname + '/'));

app.get('/', function (req, res) {

    res.sendfile(__dirname + '/index.html');
});
var waiting = {};
var number = 0;
io.on('connection', function (socket) {
  socket.cid = new Date().getTime();  
  waiting[socket.cid] = socket.id;
	number++;
	console.log("connection"+number+"-"+waiting);
	// console.log(io.sockets);

  if (socket.cid%2==0) {
    socket.join('room000', () => {

    }); 
  }

  socket.on('disconnect', (reason) => {
    delete waiting[socket.cid];
    // waiting[socket.cid] = null;
   console.log("lost-"+reason+"-"+socket.cid+"-"+waiting);
  });
  socket.on('state',function(data){
    socket.emit("message",{state:waiting});
  });
  socket.on('room',function(data){
    socket.broadcast.to("room000").emit("roomMessage",data);
  });
  socket.on('message',function(data){
    if (data.uid&&waiting[data.uid]) {
      data['from'] = socket.cid;
      console.log(data);
      socket.to(waiting[data.uid]).emit("message",data);
    }else{
      console.log("no")
    }
  });

    
  // setTimeout(function(){
  // 	socket.disconnect(true);
  // },10000)

});